<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { SystemDeptApi } from '#/api/system/dept';
import type { SystemUserApi } from '#/api/system/user';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { COMMON_OPT } from '@vben/constants';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';

import { ElButton, ElLoading, ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteUser,
  deleteUserList,
  exportUser,
  getUserPage,
  updateUserStatus,
} from '#/api/system/user';
import DoubleColumnLayout from '#/components/DoubleColumnLayout/index.vue';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import AssignRoleForm from './modules/assign-role-form.vue';
import DeptTree from './modules/dept-tree.vue';
import Form from './modules/form.vue';
import ImportForm from './modules/import-form.vue';
import ResetPasswordForm from './modules/reset-password-form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [ResetPasswordModal, resetPasswordModalApi] = useVbenModal({
  connectedComponent: ResetPasswordForm,
  destroyOnClose: true,
});

const [AssignRoleModal, assignRoleModalApi] = useVbenModal({
  connectedComponent: AssignRoleForm,
  destroyOnClose: true,
});

const [ImportModal, importModalApi] = useVbenModal({
  connectedComponent: ImportForm,
  destroyOnClose: true,
});

/** 刷新表格 */
function handleRefresh() {
  gridApi.query();
}

/** 导出表格 */
async function handleExport() {
  const data = await exportUser(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: '用户.xls', source: data });
}

/** 选择部门 */
const searchDeptId = ref<number | undefined>(undefined);
async function handleDeptSelect(dept: SystemDeptApi.Dept) {
  searchDeptId.value = dept.id;
  handleRefresh();
}

/** 创建用户 */
function handleCreate() {
  formModalApi.setData(null).open();
}

/** 导入用户 */
function handleImport() {
  importModalApi.open();
}

/** 编辑用户 */
function handleEdit(row: SystemUserApi.User) {
  row.OPT_TYPE = COMMON_OPT.UPDATE;
  formModalApi.setData(row).open();
}
/** 复制用户 */
function handleCopy(row: SystemUserApi.User) {
  row.OPT_TYPE = COMMON_OPT.COPY;
  formModalApi.setData(row).open();
}
/** 删除用户 */
async function handleDelete(row: SystemUserApi.User) {
  ElMessageBox.confirm(`确定删除用户【${row.nickname}】吗`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: $t('ui.actionMessage.deleting', [row.nickname]),
        spinner: 'el-icon-loading', // 使用内置图标名
        background: 'rgba(0, 0, 0, 0.7)',
      });
      deleteUser(row.id!)
        .then(() => {
          ElMessage.success(
            $t('ui.actionMessage.deleteSuccess', [row.nickname]),
          );
          handleRefresh();
        })
        .finally(() => {
          loadingInstance.close();
        });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
}

/** 批量删除角色 */
async function handleDeleteBatch() {
  ElMessageBox.confirm(`确定删除选中的用户吗`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: $t('ui.actionMessage.deleting'),
        spinner: 'el-icon-loading', // 使用内置图标名
        background: 'rgba(0, 0, 0, 0.7)',
      });
      deleteUserList(checkedIds.value)
        .then(() => {
          ElMessage.success($t('ui.actionMessage.deleteSuccess'));
          handleRefresh();
        })
        .finally(() => {
          loadingInstance.close();
        });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      });
    });
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: SystemUserApi.User[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}

/** 重置密码 */
function handleResetPassword(row: SystemUserApi.User) {
  resetPasswordModalApi.setData(row).open();
}

/** 分配角色 */
function handleAssignRole(row: SystemUserApi.User) {
  assignRoleModalApi.setData(row).open();
}

/** 更新用户状态 */

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
    collapsed: true,
  },
  gridOptions: {
    columns: useGridColumns(onActionClick, handleStatusChange),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getUserPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
            deptId: searchDeptId.value,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      search: true,
      custom: true,
      export: false,
      refresh: true,
      zoom: true,
    },
  } as VxeTableGridOptions<SystemUserApi.User>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<SystemUserApi.User>) {
  switch (code) {
    case 'assignRoles': {
      handleAssignRole(row);
      break;
    }
    case 'copy': {
      handleCopy(row);
      break;
    }
    case 'delete': {
      handleDelete(row);
      break;
    }
    case 'edit': {
      handleEdit(row);
      break;
    }
    case 'resetPwd': {
      handleResetPassword(row);
      break;
    }
  }
}
/**
 * 状态开关即将改变
 * @param newStatus 期望改变的状态值
 * @param row 行数据
 * @returns 返回false则中止改变，返回其他值（undefined、true）则允许改变
 */
async function handleStatusChange(newStatus: number, row: SystemUserApi.User) {
  try {
    await updateUserStatus(row.id!, newStatus);
    return true;
  } catch {
    return false;
  }
}
</script>

<template>
  <DoubleColumnLayout>
    <template #left>
      <DeptTree @select="handleDeptSelect" />
    </template>
    <template #right>
      <FormModal @success="handleRefresh" />
      <ResetPasswordModal @success="handleRefresh" />
      <AssignRoleModal @success="handleRefresh" />
      <ImportModal @success="handleRefresh" />
      <Grid table-title="用户列表">
        <template #toolbar-tools>
          <ElButton type="primary" @click="handleCreate"> 新增 </ElButton>
          <ElButton type="primary" @click="handleExport"> 导出 </ElButton>
          <ElButton type="primary" @click="handleImport"> 导入 </ElButton>
          <ElButton
            type="danger"
            @click="handleDeleteBatch"
            :disabled="isEmpty(checkedIds)"
          >
            批量删除
          </ElButton>
        </template>
      </Grid>
    </template>
  </DoubleColumnLayout>
</template>
<style scoped></style>
